package logic;

import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.DataElement;
import javax.bluetooth.ServiceRecord;
import javax.microedition.lcdui.AlertType;

/**
 * class for establishind the connection with given device from the list of previously found devices
 * @author Rekin
 *
 */
public class BluetoothServerConnectionHandler extends Thread{
	
	private Vector selectedDevices;
	
	/**
	 * default constructor
	 * @param checkedServiceRecords devices checked for connection to within the list view
	 */
	public BluetoothServerConnectionHandler(Vector checkedServiceRecords){
		selectedDevices=checkedServiceRecords;
	}

	/* (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	public void run() {
		BluetoothConnection[] btCon=new BluetoothConnection[selectedDevices.size()];
		try{
			for(int i=0;i<selectedDevices.size();++i){
				ServiceRecord sr = (ServiceRecord)selectedDevices.elementAt(i);
				String connectionUrl = sr.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
				DataElement de = sr.getAttributeValue(LogicHelper.SERVICE_NAME_PARAM);
				String rname = (String)de.getValue(); //name of remote BT device
				//String localName = LocalDevice.getLocalDevice().getFriendlyName();
				String localName=MainMidlet.getTempSettings().getPlayerName();
				btCon[i] = new BluetoothConnection(connectionUrl, localName, rname);
				btCon[i].writeString(localName); //send my host-name to client
			}
		}
		catch(IOException e){
			LogicHelper.makePopup("Error", e.getMessage(), 2000, AlertType.ERROR);
		}
		devicesConnected(btCon);
	}
	
	/**
	 * informs the midlet that connection to device was established and sets the connection handler for midlet
	 * @param connections list of established connections
	 */
	public void devicesConnected(BluetoothConnection[] connections){
		MainMidlet.getMidletInstance().setBluetoothCommunicationHandler(
				new BluetoothCommunicationHandler(connections, true));
		MainMidlet.getMidletInstance().startMultiplayerBluetoothGame();
		
	}
}
